//
//  MHAsiNetworkHandler.m
//  MHProject
//
//  Created by Sunny on 15/4/23.
//  Copyright (c) 2015年 Sunny. All rights reserved.
//

#import "SMAFNetworkHandler.h"
#import "SMAFNetworkItem.h"
@interface SMAFNetworkHandler ()<SMAFNetworkDelegate>

@end;
@implementation SMAFNetworkHandler

+ (SMAFNetworkHandler *)sharedInstance
{
    static SMAFNetworkHandler *handler = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        handler = [[SMAFNetworkHandler alloc] init];
        
        NSURL *url = [NSURL URLWithString:kUrl];
        
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        
        handler.sessionManager = [[AFHTTPSessionManager alloc] initWithBaseURL:url sessionConfiguration:config];
        
        handler.sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
        
        handler.sessionManager.requestSerializer.timeoutInterval = SMAF_API_TIME_OUT;
        
        handler.sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
        
    });
    return handler;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.networkError = NO;
    }
    return self;
}

#pragma mark - 创建一个网络请求项
/**
 *  创建一个网络请求项
 *
 *  @param url          网络请求URL
 *  @param networkType  网络请求方式
 *  @param params       网络请求参数
 *  @param delegate     网络请求的委托，如果没有取消网络请求的需求，可传nil
 *  @param showHUD      是否显示HUD
 *  @param successBlock 请求成功后的block
 *  @param failureBlock 请求失败后的block
 *
 *  @return 根据网络请求的委托delegate而生成的唯一标示
 */
- (SMAFNetworkItem *)conURL:(NSString *)url
                networkType:(SMAFNetWorkType)networkType
                     params:(NSMutableDictionary *)params
                  requestId:(NSString *) requestId
                   delegate:(id)delegate
                    showHUD:(BOOL)showHUD
                     target:(id)target
                     action:(SEL)action
               successBlock:(SMAFSuccessBlock)successBlock
               failureBlock:(SMAFFailureBlock)failureBlock
{
    if (self.networkError == YES) {
        [MBProgressHUD showActiveMessage:@"网络连接断开,请检查网络!" withBackground:NO];
        if (failureBlock) {
            failureBlock(nil,nil,nil);
        }
        return nil;
    }
    /// 如果有一些公共处理，可以写在这里
    NSUInteger hashValue = [delegate hash];
    self.netWorkItem = [[SMAFNetworkItem alloc]initWithtype:networkType url:url params:params delegate:delegate target:target action:action hashValue:hashValue showHUD:showHUD successBlock:successBlock failureBlock:failureBlock];
    self.netWorkItem.delegate = self;
    self.netWorkItem.requestId = requestId;
    [self.items setObject:_netWorkItem forKey:requestId];
    return self.netWorkItem;
}

#pragma makr - 开始监听网络连接

+ (void)startMonitoring
{
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    // 2.设置网络状态改变后的处理
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了, 就会调用这个block
        switch (status)
        {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                ITTDPRINT(@"未知网络");
                [SMAFNetworkHandler sharedInstance].networkError = NO;
                break;
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
            {
                [SMAFNetworkHandler sharedInstance].networkError = YES;
                [MBProgressHUD showActiveMessage:@"网络未连接" withBackground:NO];
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                ITTDPRINT(@"手机自带网络");
                [SMAFNetworkHandler sharedInstance].networkError = NO;
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                ITTDPRINT(@"WIFI");
                [SMAFNetworkHandler sharedInstance].networkError = NO;
                break;
        }
    }];
    [mgr startMonitoring];
}
/**
 *   懒加载网络请求项的 items 字典
 *
 *   @return 返回一个字典
 */
- (NSMutableDictionary *)items
{
    if (!_items) {
        _items = [NSMutableDictionary dictionary];
    }
    return _items;
}
/**
 *   取消所有正在执行的网络请求项
 */
+ (void)cancelAllNetItems
{
    SMAFNetworkHandler *handler = [SMAFNetworkHandler sharedInstance];
    
    for (NSDictionary *item in handler.items) {
        
        NSArray *singleRequest = [item allValues];
        
        for (SMAFNetworkItem *itm in singleRequest) {
            if ([itm isKindOfClass:[SMAFNetworkItem class]]) {
                [itm.currentTask cancel];
            }
        }
    }
    [handler.items removeAllObjects];
    handler.netWorkItem = nil;
}
/**
 *  移除一个请求
 *
 *  @param resultId 请求ID
 */
+ (void)cancelRequestForRequestId:(NSString *)resultId {

    SMAFNetworkHandler *handler = [SMAFNetworkHandler sharedInstance];
    
    SMAFNetworkItem *item = [handler.items objectForKey:resultId];
    [item.currentTask cancel];
    [handler.items removeObjectForKey:handler];
    
}

- (void)netWorkWillDealloc:(SMAFNetworkItem *)itme
{
    
    [itme.currentTask cancel];
    [self.items removeObjectForKey:itme.requestId];
    self.netWorkItem = nil;
}
@end
